<?php
/* Require the bundles ? */
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/javascriptpacker.php');
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/csspacker.php');

class admin {
	var $debug=false;
	var $site_settings;
	var $obfusticateJs=false;
	function __construct() {
		$this->getSiteSettings();
		//$this->checkSecurity();	
	}
	function __destruct() {
		
		
	}
	function checkSecurity($path) {
		// pass it the URL to look up hahahahaah
		$user=$this->getUser($_SESSION['user_id']);
		$page=$this->getAdminPage($path);
		if(empty($page['_id'])) {
			return true;	// allows for pages not in the index i.e modules by idiots that forgot to add administration of the module
		}
		
		foreach($user['groups'] as $val) {
			if(in_array($val,$page['groups'])) {
				return true;
			}
		}
		return false;
	}
	function canView($path) {
		if(!$this->checkSecurity($path) || empty($_SESSION['user_id']) || !$_SESSION['logged_in']) {
			exit("<h2>You do not have permission to do that.</h2>");			
		} 
	}
	function getAdminPage($path) {
		$data=new database();	
		$data->db(DATABASE)->collection('admin_pages');
		
		$data->criteria(array('path'=>$path));
		$row=$data->findOne();
		$data->close();
		
		return $row;
	}
	function getGroups($input='') {
		// input is an array
		$data=new database();
		$data->db(DATABASE)->collection('groups');
		$data->criteria(array('name'=>array('$nin'=>array('Administrators'))))->sort(array('name'=>1));
		$rows=$data->findNl();
		$data->close();
		foreach($rows['results'] as $row) {
			$checked=(in_array((string)$row['_id'],$input)) ? true : false;
			$output[]=array('_id'=>(string)$row['_id'],'label'=>$row['name'],'value'=>(string)$row['_id'],'checked'=>$checked);
		
		}
		return $output;
	}
	function getAdminGroup() {
		$data=new database();
		$data->db(DATABASE)->collection('groups');
		$data->criteria(array('name'=>'Administrators'));
		$row=$data->findOne();
		return (string)$row['_id'];	
	}

	function getUser($id) {
		$data=new database();
		$data->db(DATABASE)->collection('users');
		$data->criteria(array('_id'=>new MongoId($id)));
		$row=$data->findOne();
		$data->close();
		return $row;
	}	
	
	function pageId($page_id) {
		$this->page_id=$page_id;
	return $this;	
	}	
	function expireCache($cachekey) {
		$mc = new Memcached();
		$mc->addServer('localhost', 11211);	
		$mc->delete($cachekey);
		if(file_exists($_SERVER['DOCUMENT_ROOT'].'/cache/'.$this->page_id.'.html')) {
			unlink($_SERVER['DOCUMENT_ROOT'].'/cache/'.$this->page_id.'.html');	
		}
	return $this;	
	}
	function jsBundlePath($path) {
		$this->jsPath=	$path;
	return $this;
	}
	function cssBundlePath($path) {
		$this->cssPath=	$path;
	return $this;
	}
	function addJs($javascript) {
		// unique this at some point to allow no adding of Extra Jquery objects and shit
		$this->javascript[]=$javascript;
	return $this;
	}
	function addCss($css) {
		$this->css[]=$css;
	return $this;	
	}
	function getSiteSettings() {
		$data=new database;
		$data->db(DATABASE)->collection('settings');
		$data->criteria(array('url'=>array('$exists'=>true)));
		//$data->cache(true)->cachekey(DATABASE.'.site');
		$row=$data->findOne();
		$data->close();
		$this->site_settings=$row;	
		return $this;
	}
	function createBundle() {
		$debug=false;
		/*
		Requires the 2 classes to be loaded
		*/
		foreach($this->javascript as $js) {
			/* Allow js strings to be added too .... */
			//echo("Adding $js to bundle\n");
			$script=file_get_contents($js);	
				if($debug==false) {
					//$myPacker = new JavaScriptPacker($script, 62, true, false);
					if($this->obfusticateJs)  {
					 $myPacker = new JavaScriptPacker($script, 62, true, false);	
					} else {
					$myPacker = new JavaScriptPacker($script, 0, true, false);	
					}
					 $packed = $myPacker->pack();
					$output[]=$packed.';';
					} else  {
						$output[]=$script.';';
					}
				
		
		
		}
		file_put_contents($this->jsPath,implode("",$output));
		unset($output);
		foreach($this->css as $css) {
				$file=file_get_contents($css);
				$css = CssMin::minify($file);
				$output[]=$css;
		}
		file_put_contents($this->cssPath,implode("\r\n",$output));
	return $this;
	}
	function createClientBundle() {
		unset($this->javascript,$this->css);
		$this->jsBundlePath($_SERVER['DOCUMENT_ROOT'].'/bundle/bundle.js');
		$this->cssBundlePath($_SERVER['DOCUMENT_ROOT'].'/bundle/bundle.css');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/jquery-1.6.2.rc1.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/forms.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/resources/client/navigation.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/resources/client/gallery.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/resources/client/functions.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/resources/client/suggestive.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/tips.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/hidden.js');
		$this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/message.js');
		$mods=$this->getActiveModules();
		foreach($mods['results'] as $module) {
			$_path=(string)$module['path'];
			foreach($module['javascript'] as $javascript) {
				$this->addJs($_SERVER['DOCUMENT_ROOT'].'/modules/'.$_path.'/'.$javascript);			
			}
			foreach($module['css'] as $css) {
				$this->addCss($_SERVER['DOCUMENT_ROOT'].'/modules/'.$_path.'/'.$css);			
			}
		//$this->addJs($_SERVER['DOCUMENT_ROOT'].'/modules/'.(string)$v['_id'].'/'.);	
		}
		unset($css,$javascript,$_path,$module,$mods);
		// allow people to register shit to add to this etc etc
		// $this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/jquery-1.6.2.rc1');
		$this->addCss($_SERVER['DOCUMENT_ROOT'].'/resources/client/suggestive.css');
		$this->addCss($_SERVER['DOCUMENT_ROOT'].'/resources/client/gallery.css');
		$this->addCss($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/tips.css');
		$this->addCss($_SERVER['DOCUMENT_ROOT'].'/themes/'.$this->site_settings['folder_path'].'/client/style.css'); 
		//echo();
		
		
		$this->createBundle();
	return $this;
	}
	function createAdminBundle() {
		unset($this->javascript,$this->css);
		$b=$this->obfusticateJs;
		$this->obfusticateJs=true;
		$this->jsBundlePath($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/bundle.js');
		$this->cssBundlePath($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/bundle.css');
		$inputs=array('jquery-1.6.2.rc1.js','json2.js','forms.js','functions.js','tabs.js','wysiwyg.js','wysiwyg.controls.js','dialogue.js','admin.js','hidden.js','message.js','suggestive.js');
			foreach($inputs as $input) {
				$this->addJs($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/'.$input);				
			}
		$css=array('style.css','tabs.css','wysiwyg.css','dialogue.css','suggestive.css');
			foreach($css as $c) {
			$this->addCss($_SERVER['DOCUMENT_ROOT'].'/admin/resources/client/'.$c);	
			}
			$mods=$this->getActiveModules();
			foreach($mods['results'] as $module) {
			$_path=(string)$module['path'];
			foreach($module['admin']['javascript'] as $javascript) {
				$this->addJs($_SERVER['DOCUMENT_ROOT'].'/modules/'.$_path.'/'.$javascript);			
			}
			foreach($module['admin']['css'] as $css) {
				$this->addCss($_SERVER['DOCUMENT_ROOT'].'/modules/'.$_path.'/'.$css);			
			}
		//$this->addJs($_SERVER['DOCUMENT_ROOT'].'/modules/'.(string)$v['_id'].'/'.);	
		}
			
			
			
			$this->createBundle();
		$this->obfusticateJs=$b;// reset the obfusticator	
		return $this;	
	}
	
	
	function showPages() {
		$data=new database;
		$data->db(DATABASE)->collection('pages');
		$data->criteria(array('text'=>array('$exists'=>true)));
		$rows=$data->findAll();
		foreach($rows['results'] as $row) {
			$parent=(empty($row['parent'])) ? '' : $row['parent'];
			$output[]=array('id'=>(string)$row['_id'],'text'=>$row['text'],'url'=>$row['url'],'children'=>$children,'parent'=>$parent,'is_parent'=>$row['is_parent']);
					
		}
	return $output;
	}
	function  getPageInformation($id) {
		$data=new database;
		$data->db(DATABASE)->collection('pages');
		$data->criteria(array('_id'=>new MongoId($id)));
		
	return $data->findOne();
	}
	function createTags($input) {
		// $input is an array
		if($input['active']==1) {
		$stopwords = array ('about', 'all', 'alone', 'also', 'am', 'and', 'as', 'at', 'because', 'before', 'beside', 'besides', 'between', 'but', 'by', 'etc', 'for', 'i', 'of', 'on', 'other', 'others', 'so', 'than', 'that', 'though', 'to', 'too', 'then', 'them', 'trough', 'until', 'now');
		/*
		$str	=	strtolower($string);
		$str 	= 	preg_replace('/[^a-z0-9\s]/', ' ', $str);
		$arr	=	array_unique(explode(" ",$str));
		$str	=	implode(" ",$arr);	
		$str	=	strip_tags($str);
		$str	=	preg_replace('#\b('.implode('|',$stopwords).')\b#e', ' ', $str);
		$str 	=   preg_replace('/\s\s+/', ' ', $str);
		*/
		
		$t=strip_tags($input['content']." ".implode(" ", $input['tags']))." ". $input['heading'];
		
		$url=$input['url'];
		$heading=$input['heading'];
		
		if($input['is_blog_post']==1) {
			// more data is expected in the input array if it's a blog post
		
				$heading='Blog &raquo; ' . $input['heading'];	
		}
		$EXERPT=preg_replace('/\[(.*?)\](.*?)\[\/(.*?)\]/im','',$input['content']);
		$tags		=	preg_replace('/\[(.*?)\](.*?)\[\/(.*?)\]/im','',$t);
		$tags=strip_tags($tags);
		$tags		=	strtolower($tags);
		$tags 		=   preg_replace('/\s\s+/', ' ', $tags);
		$tags		=	preg_replace('/[^a-z0-9\s]/', ' ', $tags);
		$tags		=	preg_replace('#\b('.implode('|',$stopwords).')\b#e', ' ', $tags);
		$tags 		=   preg_replace('/\s\s+/', ' ', $tags);
		$excerpt=$this->truncate($EXERPT,300);
		$the_tags	=	explode(" ",$tags);
		$arr=array_unique($the_tags);
		unset($tags);
		foreach($arr as $key=>$val) {
			if(strlen($val)>=3) {
				$tags[]=$val;	
			}
		}
		$data=new database();
		$data->db(DATABASE)->collection('search_index');
		$data->criteria(array('page_id'=>$this->page_id))->remove();
		$data->criteria(array('page_id'=>$this->page_id,'tags'=>$tags,'excerpt'=>trim($excerpt),'url'=>$url,'heading'=>$heading))->insert();
		
		
		$data->close();
		}
	return $this;	
	}
	function updateContent($arr) {
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$data->criteria($arr);
		$this->createTags($arr['$set']);
		$data->update($this->page_id);	
		$data->close();		
	$cachekey=DATABASE.'cached_page_'.$this->page_id;
		$this->expireCache($cachekey)->expireCache(DATABASE.'.current_theme');
		$this->createClientBundle();
	unset($this->page_id);
	
	
	return $this;	
	}
	function updateBlogPost($arr) {
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$data->criteria($arr);
		$this->createTags($arr['$set']);
		$data->update($this->page_id);	
		$data->close();		
		$cachekey=DATABASE.'cached_page_'.$this->page_id;
		$this->expireCache($cachekey);
		$this->createClientBundle();
	unset($this->page_id);
	return $this;	
	}
	function selectYesNo($input='') {
		$options=array('Yes'=>1,'No'=>0);
		foreach($options as $key=>$val) {
			$selected=($input==$val) ? ' selected="selected"' : '';
			$output[]='<option value="'.$val.'"'.$selected.'>'.$key.'</option>';	
		}
	return implode("\r\n",$output);
	}
	function savePage($page) {
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$data->criteria($page);
		$data->update($this->page_id);
		$data->close();
		return $this;
	}
	function saveMeta($meta) {
		$data=new database();
		$data->db(DATABASE)->collection('meta_data');
		$data->criteria($meta);
		//->cache(true)->cachekey(DATABASE.'meta_'.$this->page_id);

		$data->updateMultiple(array('page_id'=>$this->page_id));
		$data->close();
		return $this;
	}
	function addContent() {
		$data=new database();
		$data->db(DATABASE)->collection('content');
		$item=array('page_id'=>$this->page_id,
				'order'=>intval(100),
				'content'=>'Please enter some content',
				'active'=>intval(0),
				'type'=>'text'
				);
		$row=$data->criteria($item)->insert();
		$data->close();
		$cachekey=DATABASE.'cached_page_'.$this->page_id;
		$this->expireCache($cachekey);
		return $row;
	}
	
	function lockAndReturnUID() {
		$data = new database();
		$data->db(DATABASE)->collection('uids');
		$row=$data->findOne();
		$uid=$row['uid'];
		$data->criteria(array('$inc' => array('uid'=>intval(1))));
		$data->update((string)$row['_id'])->close();
	return $uid;
}
	function addBlogPost($item) {
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$row=$data->criteria($item)->insert(); // add to search index...
		$this->pageId((string)$row['_id']);
		$data->close();
		$this->createTags($item);
		$cachekey=DATABASE.'cached_page_'.$this->page_id;
		$this->expireSiteCache();
		return $row;
	}
	function addPage($item) {
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$data->criteria($item);
		$row=$data->insert();
		$admin_group=$this->getAdminGroup();
		$data->close();
		$data=new database();
		$data->db(DATABASE)->collection('admin_pages');
		$data->criteria(array('$addToSet' => array("groups" => $admin_group)));
		$data->updateMultiple(array('path'=>$item['url'],'role'=>'page','name'=>$item['text']));
		$data->close();
		$this->expireSiteCache();
		return $row;
	}
	function expireSiteCache() {
		apc_clear_cache();
  		apc_clear_cache('user');
  		apc_clear_cache('opcode');

		
		$data=new database();
		$data->db(DATABASE)->collection('pages');
	//	$data->criteria(array('active'=>);	
		$data->criteria(array('active'=>array('$exists'=>true)));
		$rows=$data->findAll();
		$data->close();
		foreach($rows['results'] as $row) {
			$id=(string)$row['_id'];
			$this->pageId($id);
			$this->expireCache(DATABASE.'cached_page_'.$id);	
		}
		unset($this->page_id);
		return $this;
	}
	function deletePage() {
		$page=$this->getPageInformation($this->page_id);
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$data->criteria(array('_id'=>new MongoId($this->page_id)))->remove();
		$data->collection('content')->criteria(array('page_id'=>$this->page_id))->remove();
		$data->collection('meta_data')->criteria(array('page_id'=>$this->page_id))->remove();
		$data->collection('tags')->criteria(array('page_id'=>$this->page_id))->remove();
		$data->collection('admin_pages')->criteria(array('path'=>$page['url']))->remove();
		
		$data->close();
		$this->expireSiteCache();
		return $this;
	}
	function getContent($id) {
		$data=new database;
		$data->db(DATABASE)->collection('content');
		$data->criteria(array('_id'=>new MongoId($id)))->sort(array('order'=>1));
		$rows=$data->findOne();
		return $rows;	
	}
	
		function zip_flatten ( $zipfile, $dest='.' )
{
    $zip = new ZipArchive;
    if ( $zip->open( $zipfile ) )
    {
       
		for ( $i=0; $i < $zip->numFiles; $i++ )
        {
            $entry = $zip->getNameIndex($i);
            if ( substr( $entry, -1 ) == '/' ) continue; // skip directories
           
            $fp = $zip->getStream( $entry );
            $ofp = fopen( $dest.'/'.basename($entry), 'w' );
           			if( !$ofp ) {
					throw new Exception('Unable to write to destination.');	
					}
           
           
            while ( ! feof( $fp ) )
             if(   fwrite( $ofp, fread($fp, 8192) ) ) {
				
			 } else {
			
			 }
          
            fclose($fp);
            fclose($ofp);
        }

        $zip->close();
    } else {
        return false;
	}
    return $zip;
}
	function getModules() {
		$data=new database();
		$data->db(DATABASE)->collection('modules');
		$data->criteria(array('name'=>array('$exists'=>true)));	
		$rows=$data->findAll();
		return $rows;
	}
	function getActiveModules() {
		$data=new database();
		$data->db(DATABASE)->collection('modules');
		$data->criteria(array('active'=>intval(1)));	
		$rows=$data->findAll();
		return $rows;	
	}
	function explode_trim($str, $delimiter = ',') {
		$str=trim($str);
		if(empty($str)) {
			return array();	
		}
    	return array_map('trim',explode($delimiter,$str));
   
	} 
	function make_slug($url) {
		$str=trim($url);
		$str=strtolower($str);
		$str=preg_replace('/\s+/',' ',$str);
		$str=trim($str);
		$str=str_replace(" ","-",$str);
		$str=preg_replace("/[^a-z]+/","-",$str);
		return $str;
	}
	function getPageContent($page_id) {
		$data=new database();
		$data->db(DATABASE)->collection('content');
		$data->criteria(array('page_id'=>$page_id,'type'=>'text'))->sort(array('order'=>1));
		$rows=$data->findNl();	
		return $rows;	
	}
	function getBlogPosts() {
		$data=new database();
		$data->db(DATABASE)->collection('pages');
		$data->criteria(array('is_blog'=>intval(1),'include_in_nav'=>intval(0)))->sort(array('timestamp'=>1));
		$rows=$data->findNl();
		$data->close();	
		return $rows;	
	}
	function truncate($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
	if ($considerHtml) {
		// if the plain text is shorter than the maximum length, return the whole text
		if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
			return $text;
		}
		// splits all html-tags to scanable lines
		preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
		$total_length = strlen($ending);
		$open_tags = array();
		$truncate = '';
		foreach ($lines as $line_matchings) {
			// if there is any html-tag in this line, handle it and add it (uncounted) to the output
			if (!empty($line_matchings[1])) {
				// if it's an "empty element" with or without xhtml-conform closing slash
				if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
					// do nothing
				// if tag is a closing tag
				} else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
					// delete tag from $open_tags list
					$pos = array_search($tag_matchings[1], $open_tags);
					if ($pos !== false) {
					unset($open_tags[$pos]);
					}
				// if tag is an opening tag
				} else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
					// add tag to the beginning of $open_tags list
					array_unshift($open_tags, strtolower($tag_matchings[1]));
				}
				// add html-tag to $truncate'd text
				$truncate .= $line_matchings[1];
			}
			// calculate the length of the plain text part of the line; handle entities as one character
			$content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
			if ($total_length+$content_length> $length) {
				// the number of characters which are left
				$left = $length - $total_length;
				$entities_length = 0;
				// search for html entities
				if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
					// calculate the real length of all entities in the legal range
					foreach ($entities[0] as $entity) {
						if ($entity[1]+1-$entities_length <= $left) {
							$left--;
							$entities_length += strlen($entity[0]);
						} else {
							// no more characters left
							break;
						}
					}
				}
				$truncate .= substr($line_matchings[2], 0, $left+$entities_length);
				// maximum lenght is reached, so get off the loop
				break;
			} else {
				$truncate .= $line_matchings[2];
				$total_length += $content_length;
			}
			// if the maximum length is reached, get off the loop
			if($total_length>= $length) {
				break;
			}
		}
	} else {
		if (strlen($text) <= $length) {
			return $text;
		} else {
			$truncate = substr($text, 0, $length - strlen($ending));
		}
	}
	// if the words shouldn't be cut in the middle...
	if (!$exact) {
		// ...search the last occurance of a space...
		$spacepos = strrpos($truncate, ' ');
		if (isset($spacepos)) {
			// ...and cut the text in this position
			$truncate = substr($truncate, 0, $spacepos);
		}
	}
	// add the defined ending to the text
	$truncate .= $ending;
	if($considerHtml) {
		// close all unclosed html-tags
		foreach ($open_tags as $tag) {
			$truncate .= '</' . $tag . '>';
		}
	}
	return $truncate;
}
	function enctypesAsOptions($input='') {
		$options=array('multipart/form-data','application/x-www-form-urlencoded','text/plain');
			foreach($options as $option) {
				$selected=($option==$input)? ' selected="selected"' : '';
				$output[]='<option value="'.$option.'"'.$selected.'>'.$option.'</option>';
			}
	return implode("\n",$output);
	
	}
	function methodsAsOptions($input='') {
		$options=array('post','get');
			foreach($options as $option) {
				$selected=($option==$input)? ' selected="selected"' : '';
				$output[]='<option value="'.$option.'"'.$selected.'>'.$option.'</option>';
			}
	return implode("\n",$output);
	
	}
	function inlineAsOptions($input='') {
		$options=array(1,0);
			foreach($options as $option) {
				$selected=($option==$input)? ' selected="selected"' : '';
				$output[]='<option value="'.$option.'"'.$selected.'>'.$option.'</option>';
			}
	return implode("\n",$output);
	
	}
	function addNewForm($criteria) {
		$token=md5($criteria['form_name'].microtime());
		$criteria['token']=$token;
		//print_r($criteria);
		$data=new database();	
		$data->db(DATABASE)->collection('forms');
		$data->criteria($criteria);
		$row=$data->insert();
		$data->close();
		file_put_contents($_SERVER['DOCUMENT_ROOT'].'/inc/form_'.$token.'.php','<?php echo("hi"); ?>');
		file_put_contents($_SERVER['DOCUMENT_ROOT'].'/inc/logic_'.$token.'.php','<?php echo("processing"); ?>');
		return $row;
	}
	function showForms() {
		$data=new database();	
		$data->db(DATABASE)->collection('forms');
		$data->criteria(array('token'=>array('$exists'=>true)))->sort(array('_id'=>1));	
		$rows=$data->findNl();
		$data->close();
		return $rows;
	}
	function getForm($id) {
		$data=new database();	
		$data->db(DATABASE)->collection('forms');
		$data->criteria(array('_id'=>new MongoId($id)));
		$row=$data->findOne();
		$data->close();
		return $row;	
	}
	function saveForm($criteria,$id) {
		$data=new database();
		$data->db(DATABASE)->collection('forms');
		$newData=array('$set'=>$criteria);
		$data->criteria($newData);
		$data->update($id);
		$data->close();
		return true;
	}
	function removeImage($id) {
		
		$data=new database();
		$data->db(DATABASE)->collection('media');	
		$data->criteria(array('_id'=>new MongoId($id)));
		$row=$data->findOne();
		$data=new database();
		$data->db(DATABASE)->collection('media');	
		$data->criteria(array('_id'=>new MongoId($id)));
		$data->remove();
		$data->close();
		unlink($_SERVER['DOCUMENT_ROOT'].$row['path']);
		unlink($_SERVER['DOCUMENT_ROOT'].$row['large']['path']);
		unlink($_SERVER['DOCUMENT_ROOT'].$row['thumb']['path']);
	return $this;
	}
	function clean($str) {
		$s=rawurldecode($str);
		$s=str_replace("£","&#163;",$s);
		$s=mb_convert_encoding($s,'UTF-8','auto');
		$s=nl2br($s);
		$s=preg_replace('/\r\n/','<br />',$s);
		return trim($s);
	}
	function saveSettings($id,$criteria) {
		$data=new database();
		$data->db(DATABASE)->collection('settings');
		$data->criteria(array('$set'=>$criteria));
		$data->update($id);
		$data->close();
		$this->getSiteSettings();
		$this->expireSiteCache();
		$this->createClientBundle();
		
	}
	function getAdminNavigation() {
		$data=new database();
		$data->db(DATABASE)->collection('admin_navigation');
		$data->criteria(array('active'=>intval(1),'is_parent'=>intval(1)))->sort(array('order'=>1));
		$rows=$data->findNl();
		$data->close();

		foreach($rows['results'] as $row) {
			$children=$this->getAdminSubNavigation((string)$row['_id']);	
			$output[]=array('_id'=>(string)$row['_id'],'label'=>$row['label'],'href'=>$row['href'],'id'=>$row['id'],'children'=>$children);
		}
		$data->close();
		return $output;
	}
	function getAdminSubNavigation($id) {
		$data=new database();
		$data->db(DATABASE)->collection('admin_navigation');
		$data->criteria(array('active'=>intval(1),'is_parent'=>intval(0),'parent'=>$id))->sort(array('order'=>1));
		$rows=$data->findNl();
		$data->close();
		return ($rows['num_results']>=1) ? $rows['results'] : '';
	
	}
	
	function deleteModule($id) {
		$data=new database();
		$data->db(DATABASE)->collection('modules');
		$data->criteria(array('_id'=>new MongoId($id)));
		$row=$data->findOne();
		$data->close();
		if(!empty($row['path'])) {
			rmdir($_SERVER['DOCUMENT_ROOT'].'/modules/'.$row['path']);/// clean up the module folder
			$data=new database();
			$data->db(DATABASE)->collection('modules');
			$data->criteria(array('_id'=>new MongoId($id)));
			$data->remove();
			$data->close();	
		}
		// we still have the row
		// remove from admin_pages, admin_navigation, and rebuild bundles
		$data=new database();
		$data->db(DATABASE)->collection('admin_navigation');
		foreach($row['admin']['navigation'] as $v) {
			$data->criteria(array('href'=>'/modules/'.$row['path'].'/'.$v))->remove();	
		}
		unset($v);
		$data->collection('admin_pages');
		foreach($row['admin']['functions'] as $v) {
			$data->criteria(array('path'=>'/modules/'.$row['path'].'/'.$v))->remove();	
		}
		$data->close();
		$this->createClientBundle()->createAdminBundle();
	}
	function listdir($dir='.',$filter='') {
    if (!is_dir($dir)) {
        return false;
    }
   
    $files = array();
    $this->listdiraux($dir, $files);
	foreach($files as $key=>$val) {
		
		$a[$key]=str_replace("//","/",$val);	
	}
    return $a;
}

function listdiraux($dir, &$files) {
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $filepath = $dir == '.' ? $file : $dir . '/' . $file;
        if (is_link($filepath))
            continue;
        if (is_file($filepath))
            $files[] = $filepath;
        else if (is_dir($filepath))
            $this->listdiraux($filepath, $files);
    }
    closedir($handle);
} 
	function filterByStrPos($array,$regex) {
		$output=array();
		foreach($array as $key=>$val) {
			if(strpos($val,$regex)) {
				array_push($output,$val);	
			}
			
		}
		return $output;
	}
	public function pagination($page_number,$num_pages,$max_pages,$path,$extra='',$class='pagination') {
if($page_number==0) {

$page_number=1;	
}
$_pn=$page_number;

	if($page_number <=1) {
		$previous='';
	} else { 
		
		$paff=str_replace("page=".$_pn,"page=".($page_number-1),$path);
		
		$previous='<a rel="'.($page_number-1).'" href="'.$paff.$extra.'" class="'.$class.' tip" title="Goto Previous Page">Prev</a>'; 
	}
	
	if( ($page_number >= $num_pages) && ($page_number >= $max_pages) ) {
		$next="";
	} else {
				$paff=str_replace("page=".$_pn,"page=".($page_number+1),$path);

		$next='<a rel="'.($page_number+1).'" href="'.$paff.$extra.'" class="'.$class.' tip" title="Goto Next Nage">Next</a>';
	}

$pn=$page_number;
	if( ($page_number-($max_pages/2)) <=1  ) {
	for($m=1;$m<$page_number;$m++)
		{
					$paff=str_replace("page=".$_pn,"page=".($m),$path);

			$left.='<a rel="'.$m.'" class="'.$class.' tip" href="'.$paff.$extra.'" title="Goto Page '.$m.'">'.$m.'</a>';
		}
	unset($m);
	} else {
	
	for($m=$page_number-ceil(($max_pages/2));$m<$page_number;$m++)
		{
			$paff=str_replace("page=".$_pn,"page=".($m),$path);
			$left.='<a rel="'.$m.'" class="'.$class.' tip" href="'.$paff.$extra.'" title="Goto Page '.$m.'">'.$m.'</a>';
		}
	
	
	}
	if( ($page_number > 1) && ($page_number-($max_pages/2) >= 1)) {
	
		if(($page_number-($max_pages/2) >= 1)) {
	} else { 	
	}
	}
	if( (($page_number + $max_pages) < $num_pages)) {
	
	
	}
	if(($page_number > 1)) {
		$paff=str_replace("page=".$_pn,"page=1",$path);
		$first='<a rel="1" href="'.$paff.$extra.'" title="Goto First Page" class="'.$class.' tip">&laquo;&laquo;</a>';
	}
	if(($page_number!=$num_pages)) {
		
		$paff=str_replace("page=".$_pn,"page=".($num_pages),$path);
		$last='<a rel="'.$num_pages.'" class="'.$class.' tip" href="'.$paff.$extra.'" title="Goto Last Page">&raquo;&raquo;</a>';
	}
	for($i=$page_number;$i<=$num_pages;$i++) {
		if( $x<($max_pages)) {
			if($page_number==0) { $page_number=1; }
			if($i!=$page_number) {
				
				if($i==0) {
				$right.="";
				} else {
				$paff=str_replace("page=".$_pn,"page=".($i),$path);
				$right.='<a rel="'.$i.'" class="'.$class.' tip" href="'.$paff.$extra.'" title="Goto Page '.$i.'">'.$i.'</a>';
				}
			} else {
				
				$paff=str_replace("page=".$_pn,"page=".($i),$path);
				$right.='<a href="'.$paff.$extra.'" class="'.$class.' '.$class.'-selected" rel="'.$i.'">'.$i.'</a>';

			}
		}
			$x++;

	}
	if($page_number==$num_pages) {
	$next="";
	}
	
if($num_pages>1) {
return $pageOutput.$first.$previous.$concatLeft.$left.$right.$concatRight.$next.$last;
	} else {
		return "";
	}
}
	
}


?>